package com.ruoyi.business.controller;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.business.domain.BuyerInfo;
import com.ruoyi.business.listener.BuyerInfoExcelListener;
import com.ruoyi.business.service.BuyerInfoService;
import com.ruoyi.business.utils.BadRequestException;
import com.ruoyi.business.utils.CommonResult;
import com.ruoyi.business.utils.WeimobUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 客户信息
 *
 * @author ty
 */
@RestController
@RequestMapping("/business/buyerInfo")
@RequiredArgsConstructor
public class BuyerInfoController extends BaseController {

    private final BuyerInfoService buyerInfoService;
    private final WeimobUtil weimobUtil;

    /**
     * 查询客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:list')")
    @GetMapping("/list")
    public TableDataInfo list(BuyerInfo buyerInfo) {
        startPage();
        List<BuyerInfo> list = buyerInfoService.selectBuyerInfoList(buyerInfo);
        return getDataTable(list);
    }


    /**
     * 查询客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:list')")
    @GetMapping("/selectAll")
    public AjaxResult selectAll(BuyerInfo buyerInfo) {
        Long widLong = Long.valueOf(buyerInfo.getWid());
        buyerInfo.setWid(widLong);
        List<BuyerInfo> list = buyerInfoService.selectBuyerInfoList(buyerInfo);
        return AjaxResult.success(list);
    }
    /**
     * 获取客户信息
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:add')")
    @Log(title = "获取客户信息", businessType = BusinessType.INSERT)
    @PostMapping("/fetchFromWeimob")
    public void fetchFromWeimob(@RequestBody List<Long> widList) {
        if (CollectionUtils.isEmpty(widList)) {
            throw new BadRequestException("客户编号不能为空！");
        }
        if (widList.size() > 20) {
            throw new BadRequestException("一次最多支持查询 20 条客户编号");
        }
        List<BuyerInfo> buyerInfos = weimobUtil.fetchFromWeimob(widList);
        //todo  只有wid，无手机号和昵称  依然会返回   这种无效数据如何处理
        if(CollectionUtils.isEmpty(buyerInfos)){
            throw new BadRequestException("调用微盟--获取客户信息接口失败");
        }
        buyerInfoService.batchInsertOrUpdateByWid(buyerInfos);
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:query')")
    @GetMapping(value = "/{wid}")
    public AjaxResult getInfo(@PathVariable("wid") Long wid) {
        return success(buyerInfoService.selectBuyerInfoByWid(wid));
    }

    /**
     * 修改客户信息
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:edit')")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BuyerInfo buyerInfo) {
        return toAjax(buyerInfoService.updateBuyerInfo(buyerInfo));
    }


    /**
     * 删除客户信息
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:remove')")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{wids}")
    public AjaxResult remove(@PathVariable Long[] wids) {
        return toAjax(buyerInfoService.deleteBuyerInfoByWids(wids));
    }


    /**
     * 导出客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:export')")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BuyerInfo buyerInfo) {
        List<BuyerInfo> list = buyerInfoService.selectBuyerInfoList(buyerInfo);
        ExcelUtil<BuyerInfo> util = new ExcelUtil<BuyerInfo>(BuyerInfo.class);
        util.exportExcel(response, list, "客户信息");
    }

    /**
     * 导入excel客户信息
     *
     * @param file
     * @return
     */
    @PreAuthorize("@ss.hasPermi('business:buyerInfo:import')")
    @Log(title = "客户信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importBuyerInfoFile")
    @ResponseBody
    public CommonResult importBuyerInfoFile(@RequestParam("file") MultipartFile file) throws IOException {
        BuyerInfoExcelListener listener = new BuyerInfoExcelListener(buyerInfoService);
        EasyExcel.read(file.getInputStream(), listener)
                .sheet()
                .headRowNumber(1)
                .doRead();
        List<String> errorList = listener.errorList;
        if (CollUtil.isNotEmpty(errorList)) {
            return CommonResult.failed("导入失败,请检查,"+listener.errorList);
        } else {
            return CommonResult.success(null);
        }
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<BuyerInfo> util = new ExcelUtil<BuyerInfo>(BuyerInfo.class);
        util.importTemplateExcel(response, "客户数据");
    }


}





